package org.glorylight.hacks.social.service;

import java.util.ArrayList;
import java.util.List;

import org.glorylight.hacks.social.data.ScrapBookData;
import org.glorylight.hacks.social.model.ScrapBook;
import org.glorylight.hacks.social.model.User;
import org.glorylight.hacks.social.util.ModelHelper;
import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class FeedService extends BaseService {

	private static final Logger log = LoggerFactory.getLogger(FeedService.class);
		
	@Autowired
	private UserService userService;
	
	public List<ScrapBookData> getFeedByUserPage(String emailAddress, int firstResult, int maxResult) {
		 log.debug("find user feeds");
		 List<User> relations = userService.findUserToConnection(emailAddress);
		 List<String> userIds = new ArrayList<String>();
		 List<ScrapBook> scrapbooks = new ArrayList<ScrapBook>();
		 List<ScrapBookData> scrapbookDatas = new ArrayList<ScrapBookData>();
		 
		 for (User u : relations)
			 userIds.add(u.getEmailAddress());
		 
		 if (!userIds.isEmpty()) {
			 scrapbooks = em.createNamedQuery("books-by-user-feed", ScrapBook.class)
					 	.setParameter("userIds", userIds)
					 	.setFirstResult(firstResult)
					 	.setMaxResults(maxResult)
					 	.getResultList();
		 }
		 
		 for (ScrapBook page: scrapbooks) {
			 Hibernate.initialize(page.getComments());
			 Hibernate.initialize(page.getVoters());
			 ScrapBookData data = ModelHelper.convertScrapBook(page);
			 data.setVoters(ModelHelper.convertScrapBookVoters(page.getVoters()));
			 data.setComments(ModelHelper.convertScrapBookComments(page.getComments()));
			 scrapbookDatas.add(data);
		 }
		 
		 return scrapbookDatas; 
	 }
}
